package com.jk.smartelderlycare.controller;

import com.jk.smartelderlycare.pojo.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

@Api(tags = "文件上传模块")
@RestController
@RequestMapping(value = "upload")
public class UploadController {

    private static final String FOLDER_PATH = "E:\\IDEA\\apache-tomcat-9.0.89\\webapps\\upload";

    @ApiOperation(value = "文件上传", httpMethod = "POST", notes = "文件上传")
    @PostMapping("/uploadFile")
    public ResponseResult uploadFile(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();//获取文件名
        fileName = getFileName(fileName);
//        String filepath = getUploadPath();//获取当前系统路径
        String filepath = FOLDER_PATH;
        if (!file.isEmpty()) {
            try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
                System.out.println("文件上传成功，文件名：" + fileName);
//                //上传到指定目录
//                return new Result(ResultCode.SUCCESS, filepath + fileName);
                //上传到获取的当前系统路径
                try {
                    InetAddress ip4 = Inet4Address.getLocalHost();//获取当前主机+ip地址
                    String hostAddress = ip4.getHostAddress();//获取ip
                    return new ResponseResult(200, "http://" + hostAddress + ":8080/upload/" + fileName);//返回一个可访问的路径.9088是当前服务端口号
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                return new ResponseResult(444, "上传失败！");
            } catch (FileNotFoundException e) {
                System.out.println("上传文件失败 FileNotFoundException：" + e.getMessage());
                return new ResponseResult(444, "上传失败！");
            } catch (IOException e) {
                System.out.println("上传文件失败 IOException：" + e.getMessage());
                return new ResponseResult(444, "上传失败！");
            }
        } else {
            System.out.println("上传文件失败，文件为空");
            return new ResponseResult(444, "上传失败！");
        }
    }

    @GetMapping("/download/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        //动态获取图片存放位置
        //        String path = getUploadPath();//获取当前系统路径
        String path = FOLDER_PATH;
        String imagePath = path + File.separator + name;
        if (!new File(imagePath).exists()) {
            return;
        }
        //response.setContentType("image/jpeg;charset=utf-8");//图片
        response.setContentType("application/octet-stream");//文件
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(name, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get(path).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }



    /**
     * 文件名后缀前添加一个时间戳
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
//        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        fileName = nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 获取当前系统路径
     */
    private String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());//默认是target/classes/
        } catch (FileNotFoundException e) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(), "static/upload/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }
}
